﻿using Common;
using System;
using System.Net;
using System.Web.Http.Filters;

namespace BaseWebApi.App_Start
{
    /// <summary>
    /// 异常处理过滤
    /// </summary>
    public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 重写基类的异常处理方法
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //2.返回调用方具体的异常信息
            if (actionExecutedContext.Exception is NotImplementedException)
            {
                //actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                actionExecutedContext.Response = JsonHelper.ErrorJson(actionExecutedContext.Exception.Message, HttpStatusCode.NotImplemented);
            }
            else if (actionExecutedContext.Exception is TimeoutException)
            {
                //actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
                actionExecutedContext.Response = JsonHelper.ErrorJson(actionExecutedContext.Exception.Message, HttpStatusCode.RequestTimeout);
            }
            //.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常，统一返回服务端错误500
            else
            {

                actionExecutedContext.Response = JsonHelper.ErrorJson(actionExecutedContext.Exception.Message, HttpStatusCode.InternalServerError);
            }

            base.OnException(actionExecutedContext);
        }
    }
}